package com.puff.jdbc.dialect;

import com.puff.jdbc.core.DBType;

public class SqlServerDialect extends Dialect {

	@Override
	public DBType getDbType() {
		return DBType.SQLSERVER;
	}

	@Override
	public PageSql buildPageSql(String sql, int pageNumber, int pageSize) {
		int end = pageNumber * pageSize;
		if (end <= 0) {
			end = pageSize;
		}
		int begin = (pageNumber - 1) * pageSize;
		if (begin < 0) {
			begin = 0;
		}
		StringBuilder sb = new StringBuilder(sql.length() + 180);
		sb.append("SELECT * FROM ( SELECT row_number() over (order by tempcolumn) temprownumber, * FROM ");
		sb.append(" ( SELECT TOP ").append("?").append(" tempcolumn=0, ");
		sb.append(sql.replaceFirst("(?i)select", ""));
		sb.append(")vip)mvp where temprownumber>").append("?");
		PageSql pageSql = new PageSql();
		pageSql.setStart(end);
		pageSql.setEnd(begin);
		pageSql.setSql(sb.toString());
		return pageSql;
	}

}